
#include "../include/sreialPort.h"
int tmp=0,hum=0,light=0;
unsigned int CID;
int tmp_min=0,tmp_max=20,hum_min=0,hum_max=15,light_min=0,linght_max=0;
extern int ID;   //发送socket fd
char Cid[50] = {0};
volatile int card_flag = 0;
int InitM0(int ID)//初始化M0
{
    int ret;
	int nSpeed, nBits, nStop;
	char nEvent;
	unsigned char rcv_buf[36];
    int buf[36];
	
	MOfd = open( "/dev/ttyUSB0", O_RDWR|O_NOCTTY);
	
	puts("uuuuuuuuuuuuu");
	if (-1 == MOfd)
	{ 
		char* dev1 = "/dev/ttyUSB1";
		MOfd = open(dev1, O_RDWR|O_NOCTTY);             
		if (-1 == MOfd)
		{
			perror("Can't Open Serial Port");
			return -1;
		}
		//perror(" 提示错误！");
		//return M0_ERR;
	}
	set_serial(MOfd,115200,8,'N',1);
	puts("sssssssssssssss");
	//cmd_anal(fd,4,5);
	while(1)
    	{
		//sleep(1);
			puts("send **********");
			if((ret=(UART0_Recv(MOfd,rcv_buf,36)))>0)
			{
				//printf("recv ok\n");
				printf("sendQt = %d\n",sendQt);
				if(sendQt != -1 && card_flag == 0)
				dataAnal(MOfd, rcv_buf,sendQt);
			}
    	}//
    	return M0_OK;	
}

int set_serial(int MOfd,int nSpeed,int nBits,char nEvent,int nStop)
{
    struct termios newttys1,oldttys1;
    if(tcgetattr(MOfd,&oldttys1)!=0) 
     {
          perror("Setupserial 1");
          return -1;
     }
     newttys1.c_cflag|=(CLOCAL|CREAD ); /*CREAD 开启串行数据接收，CLOCAL并打开本地连接模式*/
     newttys1.c_cflag &=~CSIZE;/*设置数据位*/
     /*数据位选择*/   
     switch(nBits)
     {
         case 7:
             newttys1.c_cflag |=CS7;
             break;
         case 8:
             newttys1.c_cflag |=CS8;
             break;
     }
    printf("bit ok\n");
    /*设置奇偶校验位*/
     switch( nEvent )
     {
         case 'O':  /*奇校验*/
             newttys1.c_cflag |= PARENB;/*开启奇偶校验*/
             newttys1.c_iflag |= (INPCK | ISTRIP);/*INPCK打开输入奇偶校验；ISTRIP去除字符的第八个比特  */
             newttys1.c_cflag |= PARODD;/*启用奇校验(默认为偶校验)*/
             break;
         case 'E':/*偶校验*/
             newttys1.c_cflag |= PARENB; /*开启奇偶校验  */
             newttys1.c_iflag |= ( INPCK | ISTRIP);/*打开输入奇偶校验并去除字符第八个比特*/
             newttys1.c_cflag &= ~PARODD;/*启用偶校验*/
             break;
         case 'N': /*无奇偶校验*/
             newttys1.c_cflag &= ~PARENB;
             break;
     }
    printf("event ok\n");
     /*设置波特率*/
    switch( nSpeed )  
    {
        case 2400:
            cfsetispeed(&newttys1, B2400);
            cfsetospeed(&newttys1, B2400);
            break;
        case 4800:
            cfsetispeed(&newttys1, B4800);
            cfsetospeed(&newttys1, B4800);
            break;
        case 9600:
            cfsetispeed(&newttys1, B9600);
            cfsetospeed(&newttys1, B9600);
            break;
        case 115200:
            cfsetispeed(&newttys1, B115200);
            cfsetospeed(&newttys1, B115200);
            break;
        default:
            cfsetispeed(&newttys1, B9600);
            cfsetospeed(&newttys1, B9600);
            break;
    }
     /*设置停止位*/
    if( nStop == 1)/*设置停止位；若停止位为1，则清除CSTOPB，若停止位为2，则激活CSTOPB*/
    {
        newttys1.c_cflag &= ~CSTOPB;/*默认为一位停止位； */
    }
    else if( nStop == 2)
    {
        newttys1.c_cflag |= CSTOPB;/*CSTOPB表示送两位停止位*/
    }
    /*设置最少字符和等待时间，对于接收字符和等待时间没有特别的要求时*/
    newttys1.c_cc[VTIME] = 0;/*非规范模式读取时的超时时间；*/
    newttys1.c_cc[VMIN]  = 0; /*非规范模式读取时的最小字符数*/
    tcflush(MOfd ,TCIFLUSH);/*tcflush清空终端未完成的输入/输出请求及数据；TCIFLUSH表示清空正收到的数据，且不读取出来 */

     /*激活配置使其生效*/
    if((tcsetattr( MOfd, TCSANOW,&newttys1))!=0)
    {
        perror("com set error");
        return -1;
    }

    return 0;
}
int UART0_Recv(int MOfd, unsigned char *rcv_buf,int data_len) //串口接收 
{
	puts("**********");
    int i,len,fs_sel;
    fd_set fs_read;
    struct timeval time;
    FD_ZERO(&fs_read);
    FD_SET(MOfd,&fs_read);
    time.tv_sec = 10;
    time.tv_usec = 0;
    fs_sel = select(MOfd+1,&fs_read,NULL,NULL,&time);
    if(fs_sel)
    {
        len = read(MOfd,rcv_buf,data_len);		
		printf("read len = %d\n",len);
	    if (len>0)
	    {
			rcv_buf[36] = '\0';
			return len;
	    }
		else
		{
			printf("11111111111111");
			//printf("%s\n",strerr(errno));
			perror("error:");
		}
    }
    else  
    {  
	    printf("Sorry,I am wrong!");  
		return -1;  
    }  
}

void dataAnal(int MOfd,unsigned char *rcv_buf,int newID)//M0数据解析
{
	puts("^^^^^^^^^^^^^");
	int i =0,j;
	unsigned char *p;
	p = rcv_buf;
	while(i<36)
	{
		if(0xCC == p[i] || 0xbb == p[i]){
			p = p+i;
			break;}
		i++;
	}
	memset(Cid, 0,sizeof(Cid));
	switch(p[0])
	{
		case 0xBB:
				{
					tmp = p[5];
					hum = p[7];
					light = p[20];
					InsertEnvironment(tmp, hum, light);
					cmp(tmp,hum,light);
				}
				break;
		case 0xCC:
				{
					puts("CCCCCCCCCCCCCCCCC");
					memcpy(&CID, p+4, 4);
					sprintf(Cid,"%d",CID);
					printf("M0----Cid****%s\n",Cid);
					//char card_buf[20] = "rid,ok";  // ID find ok
					if(DB_OK == FindCard(Cid))
					{
						card_flag = 1;
						puts("card********");
						cmd_anal(MOfd,5,5);		
						sleep(2);
						cmd_anal(MOfd,6,5);
						card_flag = 0;
					}
				}
				break;
	}
}
void cmd_anal(int MOfd,int cmd_num,unsigned char id)
{
    //unsigned char send_buf[36] = {0xdd,0x00,0x24,0x00};
	//unsigned char send_buf[36] = {0};
	unsigned char send_buf[1] = {0};
    int i=0;
	//printf("cmd\n");
	//send_buf[1]=id;
	switch(cmd_num)
	{
		case 1:
			send_buf[0]=0x01;
			UART0_Send(MOfd,send_buf,1);
			break;
		case 2:
			send_buf[0]=0x02;
			UART0_Send(MOfd,send_buf,1);
			break;
		case 3:
			send_buf[0]=0x03;
			UART0_Send(MOfd,send_buf,1);
			//UART0_Send(MOfd,"3",1);
			break;
		case 4:
			send_buf[0]=0x04;
			UART0_Send(MOfd,send_buf,1);
			break;
		case 5:
			send_buf[0]=0x05;
			UART0_Send(MOfd,send_buf,1);
			break;
		case 6:
			send_buf[0]=0x06;
			UART0_Send(MOfd,send_buf,1);
			break;
		default:
			break;
	}
}
int UART0_Send(int MOfd, unsigned char *send_buf,int data_len)//串口发送    
{
    int len = 0;     
    len = write(MOfd,send_buf,data_len);    
    if (len == data_len )    
    {   
		int i=0;
		printf("send_buf = %x\t",send_buf[0]);
		/*for(i=0;i<6;i++)
		{
			printf("send_buf = %x\t",send_buf[i]);
			//fflush(stdout);
		}*/
        return len;    
    }         
    else       
    {     
        tcflush(MOfd,TCOFLUSH);    
        return -1;    
    }         
}    
